function parse212(message) {
  /**
   * ##
   * 0158
   * QN=20230704115100000;
   * ST=31;CN=2011;
   * PW=123456;
   * MN=41010501G00002;
   * Flag=4;
   * CP=&&DataTime=20230704115100;f0005-Rtd=0.36,f0005-Flag=N;f10012-Rtd=0.02,f10012-Flag=N&&
   * F441
   **/
  const fields = {};

  if (message.startsWith("##")) {
    message = message.substring(6);
  }

  let cpStart = message.indexOf("&&");
  let cpEnd = message.indexOf("&&", cpStart + 2);

  if (cpStart > -1 && cpEnd > -1) {
    let cpStr = message.substring(cpStart + 2, cpEnd);
    if (cpStr) {
      fields.CP = cpStr;
    }
    message = message.substring(0, cpStart - 3);
  }

  // 分割报文
  const parts = message.split(";");

  // 遍历每个字段
  parts.forEach((part) => {
    const [key, value] = part.split("=");
    if (key && value) {
      fields[key] = value;
    }
  });

  return fields;
}

// 解析函数
function parseCP(cp) {
  const fields = {};

  // 移除多余的前后空格和分隔符
  const trimmedCp = cp.trim().replace(/^&&/, "").replace(/&&$/, "");

  // 遍历每个字段
  trimmedCp.split(";").forEach((part) => {
    part.split(",").forEach((item) => {
      const [key, value] = item.split("=");
      fields[key] = value;
    });
  });

  return fields;
}

function parse212Data(message) {
  let data212 = parse212(message);

  data212._cpData = parseCP(data212.CP);

  return data212;
}

export default {
  parse212Data,
};
